﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Practices.ServiceLocation;
using System.Diagnostics;

namespace AzureToolkit.Engine
{
    internal class BatchMessageHandler<TMessage> : MessageHandlerBase<TMessage>, IMessageHandler where TMessage : IAzureQueueMessage
    {

        public BatchMessageHandler(MessageHandlerSettings settings)
            : base(settings)
        {
        }

        protected override bool Cycle()
        {
            try
            {
                var messages = this.Queue.GetMessages(this.Settings.BatchSize);
                if (messages.Count > 0)
                {
                    var batchCommand = (IBatchCommand<TMessage>)ServiceLocator.Current.GetInstance(Settings.CommandType);
                    try
                    {
                        batchCommand.PreRun();
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.TraceInformation());
                        return true;
                    }

                    // Process messages
                    ProcessMessages(messages, batchCommand.Run);

                    try
                    {
                        batchCommand.PostRun();
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.TraceInformation());
                        return true;
                    }
                }

                Thread.Sleep(this.Settings.IntervalBetweenRuns);
                return messages.Count > 0;
            }
            catch (TimeoutException)
            {
                return true;
            }
        }

    }
}
